<template>
	<el-upload :class="{disabled: !isShowUploadBtn}"
		action="null"
		:multiple="isMulti"
		:auto-upload="false"
		:accept="accept"
		:show-file-list="showFileList"
		:list-type="listType"
		:disabled="disabled"
		:limit="limit"
		:drag="drag"
		:size="size"
    :file-list="fileList"
    :before-remove="beforeRemove"
		:on-change="handleChange"
	>
		<slot></slot>
	</el-upload>
</template>

<script>
	import JdldUpload from './js/upload.js'

	export default {
		name: 'jdldUpload',
		props: {
		  //显示隐藏上传按钮，默认显示
      isShowUploadBtn: {
        type: Boolean,
        default: true
      },
      //上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
      fileList: {
        type: Array,
        default() {
          return [];
        }
      },
      //删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
      beforeRemove: Function,
			isMulti: {
				type: Boolean,
				default: false
			},
			minSize: {
				type: Number,
				default: 300
			},
			chunkSize: {
				type: Number,
				default: 100
			},
			threadCount: {
				type: Number,
				default: 5
			},
			accept: {
				type: String,
				default: ''
			},
			showFileList: {
				type: Boolean,
				default: false
			},
			listType: {
				type: String,
				default: 'text'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			limit: {
				type: Number,
				default: null
			},
			drag: {
				type: Boolean,
				default: false
			},
			size: {
				type: Number,
				default: 0
			},
			onSuccess: {
				type: Function,
				required: true
			},
			onError: {
				type: Function
			},
			onProgress: {
				type: Function
			},
			//上传文件超过限制大小时 回调函数
			onGtSize: {
				type: Function
			}
		},
		data: function() {
			return {
				opts:null
			}
		},
		methods: {
			handleChange(file, fileList) {
				if(this.size != 0 && this.size*1024 < file.raw.size) {
					if(this.onGtSize != undefined && this.onGtSize != null) {
						var resp = {id:file.uid, originName:file.raw.name};
						this.onGtSize(resp);
					}
				}else {
					JdldUpload.get_md5(file.raw, file.uid, this.opts);
				}
			}
		},
		created(){

			var options = {
				clientId: this.Jdld$Global.clientId,
				clientKey: this.Jdld$Global.clientKey,
				domain: this.Jdld$Global.domain,
				minSize: this.minSize,
				chunkSize: this.chunkSize,
				threadCount: this.threadCount,
				onSuccess: this.onSuccess
			}
			if(this.onProgress != undefined && this.onProgress != null) {
				options.onProgress = this.onProgress;
			}
			if(this.onError != undefined && this.onError != null) {
				options.onError = this.onError;
			}
			this.opts = options;
			JdldUpload.init(options);
		}
	}
</script>
<style>
  .disabled .el-upload.el-upload--picture-card {
    display: none !important;
  }
  .disabled .el-button--success.is-plain {
    display: none !important;
  }
</style>
